//! # 消息总线监控系统演示
//!
//! 演示监控系统的核心功能，包括指标收集、健康检查、性能分析等

use rustcloud_bus::{
    monitoring::{
        InMemoryMonitor, MonitoringConfig, Monitor, SystemHealthChecker,
        HealthChecker, ComponentHealth, HealthStatus,
    },
    memory::InMemoryMessageBus,
    message::Message,
    bus::MessageBus,
    error::MessageBusResult,
};
use async_trait::async_trait;
use serde_json::json;
use std::collections::HashMap;
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::time::sleep;
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt, EnvFilter};

/// 自定义健康检查器 - 消息总线检查器
struct MessageBusHealthChecker {
    bus: Arc<InMemoryMessageBus>,
}

#[async_trait]
impl HealthChecker for MessageBusHealthChecker {
    async fn check_health(&self) -> ComponentHealth {
        match self.bus.stats().await {
            Ok(stats) => {
                let status = if stats.total_failed > stats.total_published / 10 {
                    HealthStatus::Warning
                } else {
                    HealthStatus::Healthy
                };
                
                ComponentHealth {
                    status,
                    message: format!("消息总线运行正常，已处理{}条消息", stats.total_published),
                    details: {
                        let mut details = HashMap::new();
                        details.insert("total_published".to_string(), stats.total_published.to_string());
                        details.insert("total_received".to_string(), stats.total_received.to_string());
                        details.insert("active_subscribers".to_string(), stats.active_subscribers.to_string());
                        details.insert("uptime_seconds".to_string(), stats.uptime_seconds.to_string());
                        details
                    },
                    last_check: chrono::Utc::now(),
                }
            }
            Err(e) => ComponentHealth {
                status: HealthStatus::Critical,
                message: format!("消息总线健康检查失败: {}", e),
                details: HashMap::new(),
                last_check: chrono::Utc::now(),
            }
        }
    }
}

/// 存储健康检查器
struct StorageHealthChecker;

#[async_trait]
impl HealthChecker for StorageHealthChecker {
    async fn check_health(&self) -> ComponentHealth {
        // 模拟存储检查
        ComponentHealth {
            status: HealthStatus::Healthy,
            message: "存储系统正常".to_string(),
            details: {
                let mut details = HashMap::new();
                details.insert("disk_usage".to_string(), "45%".to_string());
                details.insert("available_space".to_string(), "2.5GB".to_string());
                details.insert("iops".to_string(), "1250/s".to_string());
                details
            },
            last_check: chrono::Utc::now(),
        }
    }
}

async fn demonstrate_monitoring_system() -> MessageBusResult<()> {
    println!("📊 消息总线监控系统演示开始\n");

    // 1. 创建监控配置
    println!("=== 1. 创建监控配置 ===");
    let config = MonitoringConfig {
        enabled: true,
        collection_interval_secs: 5, // 5秒收集一次，演示用
        health_check_interval_secs: 10, // 10秒检查一次
        metrics_retention_hours: 1,
        latency_sample_size: 100,
        alert_thresholds: rustcloud_bus::monitoring::AlertThresholds {
            error_rate_threshold: 5.0,
            latency_threshold_ms: 100.0,
            throughput_drop_threshold: 20.0,
            memory_usage_threshold: 80.0,
            cpu_usage_threshold: 80.0,
        },
    };

    println!("✅ 监控配置:");
    println!("   • 收集间隔: {}秒", config.collection_interval_secs);
    println!("   • 健康检查间隔: {}秒", config.health_check_interval_secs);
    println!("   • 错误率阈值: {}%", config.alert_thresholds.error_rate_threshold);
    println!("   • 延迟阈值: {}ms", config.alert_thresholds.latency_threshold_ms);

    // 2. 创建监控器
    println!("\n=== 2. 创建监控器 ===");
    let monitor = InMemoryMonitor::new(config);
    
    // 注册健康检查器
    monitor.register_health_checker(
        "system".to_string(),
        Box::new(SystemHealthChecker)
    ).await;
    
    monitor.register_health_checker(
        "storage".to_string(),
        Box::new(StorageHealthChecker)
    ).await;

    println!("✅ 监控器创建成功，已注册2个健康检查器");

    // 3. 创建消息总线用于演示
    println!("\n=== 3. 创建测试消息总线 ===");
    let bus = Arc::new(InMemoryMessageBus::new().await?);
    
    // 注册消息总线健康检查器
    monitor.register_health_checker(
        "message_bus".to_string(),
        Box::new(MessageBusHealthChecker {
            bus: bus.clone()
        })
    ).await;

    println!("✅ 测试消息总线创建成功");

    // 4. 模拟消息处理并记录指标
    println!("\n=== 4. 模拟消息处理 ===");
    
    let monitor_arc = Arc::new(monitor);
    
    // 创建订阅者
    let subscriber = bus.subscribe("test.events.*").await?;
    
    // 模拟消息发布和处理
    for i in 1..=20 {
        let start_time = Instant::now();
        
        // 发布消息
        let message = Message::new(
            &format!("test.events.item_{}", i),
            json!({"id": i, "data": format!("test_data_{}", i)})
        );
        
        let topic = message.topic().to_string();
        bus.publish(message).await?;
        
        let publish_duration = start_time.elapsed();
        
        // 记录发布指标
        monitor_arc.record_message_published(&topic, publish_duration).await;
        
        // 模拟处理延迟
        let process_start = Instant::now();
        sleep(Duration::from_millis(10 + (i % 50))).await; // 10-60ms随机延迟
        let process_duration = process_start.elapsed();
        
        // 模拟处理成功/失败
        let success = i % 7 != 0; // 每7个消息一个失败
        monitor_arc.record_message_processed(&topic, success, process_duration).await;
        
        if !success {
            monitor_arc.record_error(
                "processing_error", 
                &rustcloud_bus::error::MessageBusError::internal_error("模拟处理失败")
            ).await;
        }
        
        println!("  📝 消息 #{}: {} - 发布{:?} - 处理{:?} - {}", 
            i, topic, publish_duration, process_duration, 
            if success { "✅" } else { "❌" }
        );
        
        // 短暂等待
        sleep(Duration::from_millis(200)).await;
    }

    // 5. 查看当前指标
    println!("\n=== 5. 查看当前监控指标 ===");
    let metrics = monitor_arc.get_metrics().await?;
    
    println!("📊 吞吐量指标:");
    println!("   • 总消息数: {}", metrics.throughput.total_messages);
    println!("   • 成功消息: {}", metrics.throughput.successful_messages);
    println!("   • 失败消息: {}", metrics.throughput.failed_messages);
    println!("   • 每秒消息数: {:.2}", metrics.throughput.messages_per_second);
    
    println!("\n⏱️  延迟指标:");
    println!("   • 平均延迟: {:.2}ms", metrics.latency.average_ms);
    println!("   • P50延迟: {:.2}ms", metrics.latency.p50_ms);
    println!("   • P95延迟: {:.2}ms", metrics.latency.p95_ms);
    println!("   • P99延迟: {:.2}ms", metrics.latency.p99_ms);
    println!("   • 最大延迟: {:.2}ms", metrics.latency.max_ms);
    
    println!("\n❌ 错误率指标:");
    println!("   • 错误百分比: {:.2}%", metrics.error_rate.error_percentage);
    println!("   • 总错误数: {}", metrics.error_rate.total_errors);
    println!("   • 错误类型分布:");
    for (error_type, count) in &metrics.error_rate.error_types {
        println!("     - {}: {}", error_type, count);
    }
    
    println!("\n💻 资源使用:");
    println!("   • CPU使用率: {:.1}%", metrics.resource_usage.cpu_usage_percent);
    println!("   • 内存使用: {:.1}MB", metrics.resource_usage.memory_usage_mb);
    println!("   • 活跃连接: {}", metrics.resource_usage.active_connections);
    println!("   • 队列长度: {}", metrics.resource_usage.queue_length);

    // 6. 执行健康检查
    println!("\n=== 6. 执行健康检查 ===");
    let health_result = monitor_arc.health_check().await?;
    
    println!("🏥 整体健康状态: {:?}", health_result.status);
    println!("⏱️  检查耗时: {}ms", health_result.check_duration_ms);
    println!("🔍 组件健康状态:");
    
    for (component, health) in &health_result.components {
        let status_icon = match health.status {
            HealthStatus::Healthy => "✅",
            HealthStatus::Warning => "⚠️",
            HealthStatus::Critical => "❌",
            HealthStatus::Unknown => "❓",
        };
        
        println!("   {} {}: {} - {}", status_icon, component, health.message, 
                 health.last_check.format("%H:%M:%S"));
        
        if !health.details.is_empty() {
            for (key, value) in &health.details {
                println!("     • {}: {}", key, value);
            }
        }
    }

    // 7. 模拟告警场景
    println!("\n=== 7. 模拟告警场景 ===");
    println!("🚨 模拟高错误率场景...");
    
    // 快速产生错误
    for i in 1..=10 {
        monitor_arc.record_error(
            "high_error_scenario", 
            &rustcloud_bus::error::MessageBusError::timeout_error("模拟超时", 5000)
        ).await;
        
        monitor_arc.record_message_processed(
            &format!("error.test.{}", i), 
            false, 
            Duration::from_millis(200)
        ).await;
    }
    
    let updated_metrics = monitor_arc.get_metrics().await?;
    println!("📈 更新后错误率: {:.2}%", updated_metrics.error_rate.error_percentage);
    
    if updated_metrics.error_rate.error_percentage > 5.0 {
        println!("🚨 告警触发：错误率 {:.2}% 超过阈值 5.0%", 
                 updated_metrics.error_rate.error_percentage);
    }

    // 8. 性能分析建议
    println!("\n=== 8. 性能分析建议 ===");
    
    let avg_latency = updated_metrics.latency.average_ms;
    let error_rate = updated_metrics.error_rate.error_percentage;
    let throughput = updated_metrics.throughput.messages_per_second;
    
    println!("📈 性能分析报告:");
    
    if avg_latency > 50.0 {
        println!("   ⚠️  延迟较高 ({:.2}ms)，建议:", avg_latency);
        println!("      • 优化消息处理逻辑");
        println!("      • 增加并发处理能力");
        println!("      • 检查资源瓶颈");
    } else {
        println!("   ✅ 延迟正常 ({:.2}ms)", avg_latency);
    }
    
    if error_rate > 5.0 {
        println!("   ⚠️  错误率偏高 ({:.2}%)，建议:", error_rate);
        println!("      • 检查错误日志");
        println!("      • 完善重试机制");
        println!("      • 加强输入验证");
    } else {
        println!("   ✅ 错误率正常 ({:.2}%)", error_rate);
    }
    
    if throughput < 10.0 {
        println!("   ⚠️  吞吐量较低 ({:.2}/s)，建议:", throughput);
        println!("      • 优化消息处理流程");
        println!("      • 增加处理并发度");
        println!("      • 检查系统资源");
    } else {
        println!("   ✅ 吞吐量正常 ({:.2}/s)", throughput);
    }

    println!("\n✅ 监控系统演示完成！");
    println!("\n💡 生产环境建议:");
    println!("   • 将监控数据导出到时序数据库 (如InfluxDB)");
    println!("   • 集成告警系统 (如Prometheus AlertManager)");
    println!("   • 创建监控仪表板 (如Grafana)");
    println!("   • 设置日志聚合和分析 (如ELK Stack)");
    
    Ok(())
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // 初始化日志
    tracing_subscriber::registry()
        .with(tracing_subscriber::fmt::layer().with_target(false))
        .with(EnvFilter::from_default_env().add_directive("rustcloud_bus=info".parse()?))
        .init();

    match demonstrate_monitoring_system().await {
        Ok(()) => {
            println!("\n💡 提示:");
            println!("   • 设置 RUST_LOG=debug 查看详细监控日志");
            println!("   • 监控系统可与Prometheus、Grafana等工具集成");
        }
        Err(e) => {
            println!("❌ 监控演示失败: {}", e);
        }
    }

    Ok(())
}